﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MongoDB.Bson;
using MongoDB.Driver;
using SignatureWebApi.Models;
namespace SignatureWebApi.Controllers
{
    /// <summary>
    /// App更新控制类
    /// </summary>
    [RoutePrefix("api/App")]
    [Authorize(Roles = "root")]
    public class AppController : ApiController
    {
        /// <summary>
        /// 获取APP更新版本
        /// </summary>
        /// <param name="model">App新版本请求模型</param>
        /// <returns>更新数据<see cref="AppUpdateModel"/></returns>
        [Route("GetAppUpdate")]
        [AllowAnonymous]
        public HttpResponseMessage GetAppUpdate([FromUri]AppUpdateRequestModel model)
        {
            
            var mongoDb = MongoDbInstanceStore.DataStoreInstance;
            var builder = Builders<AppUpdateModel>.Filter;
            var filter = builder.Empty;
            if (model?.versionCode != null)
            {
                filter &= builder.Eq("versionCode", model.versionCode);
            }
            var sortBuilder = Builders<AppUpdateModel>.Sort;
            var sort = sortBuilder.Descending("updateTime");
            var dBdata = mongoDb.GetDataSingel<AppUpdateModel, AppUpdateModel>("DataStore", "AppUpdate", filter,null,sort) as IEnumerable<AppUpdateModel>;
            var temp = dBdata.ToList()[0];
            return Request.CreateResponse(HttpStatusCode.OK, temp);
        }
        /// <summary>
        /// 设置新的更新信息
        /// </summary>
        /// <param name="model">App新版本信息模型</param>
        /// <returns></returns>
        [Route("SetNewUpdateMsg")]
        public HttpResponseMessage SetNewUpdateMsg(AppUpdateModel model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            
            var mongoDb = MongoDbInstanceStore.DataStoreInstance;
            var builder = Builders<AppUpdateModel>.Filter;
            var filter = builder.Empty;
            filter &= builder.Eq("versionCode", model.versionCode);

            var dataCount = mongoDb.CountData("DataStore", "AppUpdate", filter);
            if (dataCount>0)
            {
                ModelState.AddModelError("error","此versionCode已存在!");
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            var addContent = model.ToBsonDocument();
            addContent.Add("updateTime",new BsonDateTime(DateTime.Now));
            var insertCount = mongoDb.InsertSingleDocument("DataStore", "AppUpdate", addContent);
            if (insertCount>0)
            {
                return Request.CreateResponse(HttpStatusCode.OK);
            }
            ModelState.AddModelError("error", "插入更新数据失败");
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        }
    }
}
